package com.victor.controller.mobile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.victor.entity.Bybookcoupon;
import com.victor.service.BybookcouponService;
import com.victor.service.MybybookcouponService;
import com.victor.utils.Msg;

@RestController
@RequestMapping("/buybook/buybookvouchers")
public class Buybookvouchers {
	@Autowired
	private BybookcouponService bService;
	@Autowired
	private MybybookcouponService mService;
	
	Map<String, Integer> map = new HashMap();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@PostMapping("/buybookcreate")
	public Msg create(String uuid) {
		map.put(uuid, 10);
		return Msg.success();
		
	}
	
	@PostMapping("/buybookget")
	public Msg get(String uuid,String userid) {
		for(Entry<String, Integer> entry : map.entrySet()) {
			if(uuid.equals(entry.getKey())) {
				if(entry.getValue()==null || entry.getValue() ==0) {
					return Msg.fail("该购书券以抢光");
				}else {
						if(mService.selMybybookByuuidAndUserid(uuid, userid)==1) {
							return Msg.fail("您已抢过了");
						}else {
							List<Bybookcoupon> bList = bService.selBybookcouponAll();
							if(bList==null || bList.isEmpty()) {
								return Msg.fail("没有库存");
							}
								int i =(int)(Math.random()*bList.size());
								Bybookcoupon bybookcoupon  =  bList.get(i);
								
								if(Integer.parseInt(bybookcoupon.getNumber())>=1) {
									int num = (entry.getValue())-1;
									entry.setValue(num);
									int qnum = Integer.parseInt(bybookcoupon.getNumber())-1;
									int newAlready_number=(Integer.valueOf(bybookcoupon.getAlready_number())+1);
									
									bService.updBybookcouponById(bybookcoupon.getId(),qnum,newAlready_number);
									Map<String, Object> map = new HashMap<>();
									map.put("bybookcouponid", bybookcoupon.getId());
									map.put("flag", 1);
									map.put("gaintime", sdf.format(new Date()));
									map.put("userid", userid);
									map.put("uuid", uuid);
									mService.insMybybookcoupon(map);
									return Msg.success();
								}
							
						}
					
					
				}
			}else {
				return Msg.fail("没有该链接");
			}
		}
		return null;
		
		
	}
}
